#!/usr/bin/env powershell

$PrefixDir = Split-Path -Parent $PSScriptRoot
Import-Module -Name "$PrefixDir/Modules/AesProvider"
Import-Module -Name "$PrefixDir/Modules/Process"

# Please see git help clone
$argprefixs = @(
    "--depth",
    "--branch",
    "--origin",
    "--reference",
    "--upload-pack",
    "--config",
    "-c"
)

$zargs = New-Object -TypeName System.Collections.ArrayList
for ($i = 1; $i -lt $args.Count; $i++) {
    [string]$arg = $args[$i]
    if ($arg.StartsWith("-")) {
        if ($argprefixs.Contains($arg)) {
            $i++
        }
        Continue
    }
    $zargs += $arg
}

$Url = $zargs[0]
$sec = [System.IO.Path]::DirectorySeparatorChar
if ($zargs.Length -eq 1 ) {
    $dir = Split-Path -Leaf $Url
    if ($dir.EndsWith(".git")) {
        $dir = $dir.Remove($dir.Length - 4, 4)
    }
    $Path = "$PWD/$dir"
    $Parent = $PWD
}
else {
    $xpath = $zargs[1]
    if ($xpath -eq ".") {
        $Path = $PWD
        $Parent = Split-Path $Path
        Set-Location "$Parent"
    }
    elseif ($xpath.Contains($sec)) {
        $xparent = Split-Path $xpath
        $leaf = Split-Path -Leaf $xpath
        $Parent = Resolve-Path $xparent -ErrorAction SilentlyContinue
        if (!$?) {
            Write-Host -ForegroundColor Red "$($error[0])"
            exit 1
        }
        $Path = "$Parent$sec$leaf"
    }
    else {
        $Parent = $PWD
        $Path = "$PWD$sec$xpath"
    }
}



# initialize modules dir


$Feature = "git secure clone feature"

Write-Host $Feature

if (Test-Path $Path) {
    $item = Get-ChildItem $Path
    if ($item.Length -ne 0) {
        Write-Host -ForegroundColor Red "fatal: destination path '$Path' already exists and is not an empty directory."
        exit 1
    }
}

$result = ProcessArgv -FilePath git -ArgumentList $args
if ($result -ne 0) {
    exit $result
}

Move-Item $Path  "$Parent/securedirtmp"|Out-Null
New-Item -ItemType Directory -Force -Path "$Path/.git"|Out-Null
Move-Item -Force "$Parent/securedirtmp"  "$Path/.git/secure"|Out-Null
$aeskey = Read-Host  "Please input aes key"

### check $aesword is success


#Resolve-Path -Relative
Push-Location -Path $PWD

$securedir = "$Path/.git/secure"

Set-Location "$securedir"

$gitfiles = @(
    ".gitmodules",
    ".gitignore",
    ".gitattributes"
)

git ls-tree -r HEAD|ForEach-Object {
    $entry = -Split $_ #  100644 blob e608e3b966e6356247a1a247b8e316f2b9d1893c	utils/keccak/keccaksum.cc
    $file = $entry[3]
    switch ($entry[1]) {
        "blob" {
            if ($gitfiles.Contains($file)) {
                Copy-Item $file -Destination "$Path/$file"
            }
            else {
                $unsfile = "$Path/$file"
                $pd = Split-Path -Path $unsfile
                $res = New-Item -ItemType Directory -Force -Path $pd
                if ($null -eq $res) {
                    Continue
                }
                $res = Restore-AesFile -File "$securedir/$file" -Key $aeskey -Destination "$unsfile"
                if ($res -ne 0) {
                    Write-Host -ForegroundColor Red "AES Decrypt $file failed"
                }
                else {
                    Write-Host -ForegroundColor Green "AES Decrypt $file done"
                }
            }
        }
        "commit" {Continue}
        "tree" {
            Write-Debug "git ls-tree -r no tree to be found !"
            New-Item -ItemType Directory -Force -Path "$Path/$file"
        }
        Default {
            Write-Host -ForegroundColor Red "unsupport: $_"
            Continue
        }
    }
}


$headcommit = git rev-parse HEAD
$message = git log --pretty=format:'%s' -n 1 $headcommit

Pop-Location
# check


&git init $Path
if ($LASTEXITCODE -ne 0) {
    exit $LASTEXITCODE
}
Set-Location $Path
&git add -A
if ($LASTEXITCODE -ne 0) {
    exit $LASTEXITCODE
}
&git commit -m "$message"
if ($LASTEXITCODE -ne 0) {
    exit $LASTEXITCODE
}

$pointer = @{}
$pointer["sid"] = $headcommit
$wid = git rev-parse HEAD
$pointer["wid"] = $wid

ConvertTo-Json -InputObject $pointer|Out-File "$Path/.git/pointer.json"

